package com.villaday.idf.custom.pop;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.m7.imkfsdk.KfStartHelper;
import com.moor.imkf.model.entity.CardInfo;
import com.villaday.idf.R;
import com.villaday.idf.custom.FillInvitateCodeDialog;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.model.LoginEntity;
import com.villaday.idf.model.Presell_detail;
import com.villaday.idf.model.Sms;
import com.villaday.idf.model.SmsEntity;
import com.villaday.idf.model.members;
import com.villaday.idf.model3.MembersEntity;
import com.villaday.idf.model3.MessageEntity;
import com.villaday.idf.model3.Messages;
import com.villaday.idf.model3.customerServiceStaffEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;

import java.util.HashMap;
import java.util.Map;

import razerdp.basepopup.BasePopupWindow;
//vip邀请码升级

public class VipYaoqingmashengjiPop extends BasePopupWindow {
    private Handler mHandler;
    private Context context;
    private Activity activity;
    private Presell_detail.BodyEntity body;
    private LoadingDialog loadingDialog;

    Gson gson = new GsonBuilder().create();

    private FillInvitateCodeDialog.InvitateCodeListener icListener;
    private final EditText et_inventCode;
    private final EditText et_phone;
    private final EditText et_code;
    private final TextView tv_send;
    private final TextView tv_bind;
    Handler handler = new Handler();

    private final int retryLimit = Constant.Integers.CodeRetryTime;//重试秒数上限
    private int timeNum = retryLimit;//获取验证码倒计时


    public VipYaoqingmashengjiPop(final Context context, final Activity activity) {
        super(context);
        this.context = context;
        this.activity = activity;
        findViewById(R.id.img_delete_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        mHandler = new Handler();


        buildAnima();
        setBackground(0);
        setOutSideDismiss(false);
        setKeepSize(true);
        setBlurBackgroundEnable(true);
        et_inventCode = findViewById(R.id.et_inventCode);
        et_phone = findViewById(R.id.et_phone);
        et_code = findViewById(R.id.et_code);
        tv_send = findViewById(R.id.tv_send);
        tv_bind = findViewById(R.id.tv_bind);

        tv_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tv_send.isSelected()) {
                    return;
                }

                if (et_phone.getText().toString().length() == 0) {
                    ToastUtil.initToast(context, "请输入手机号码");
                } else {
                    tv_send.setSelected(true);
                    sendMsg();
                }
            }
        });

        tv_bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_inventCode.getText().toString().length() == 0) {
                    ToastUtil.initToast(context, "请输入邀请码");

                } else if (et_phone.getText().toString().length() == 0) {
                    ToastUtil.initToast(context, "请输入手机号码");
                } else if (et_code.getText().toString().length() == 0) {
                    ToastUtil.initToast(context, "请输入验证码");
                } else {

                    loadingDialog = LoadingDialog.newInstance("绑定中...");
                    loadingDialog.show(activity.getFragmentManager());
                    Map<String, Object> map = new HashMap<>();
                    members members = new members(4, et_phone.getText().toString(), et_code.getText().toString(), et_inventCode.getText().toString());
                            OkHttpUtil.postJson(context, Constant.URL.members, new members(4, et_phone.getText().toString(), et_code.getText().toString(), et_inventCode.getText().toString()), map, new OkHttpUtil.OnDataListener() {
                                @Override
                                public void onResponse(String url, String json) {
                                    dismissLoading();
                                    LogeUtil.e("members", json);
                                    MembersEntity se = gson.fromJson(json, MembersEntity.class);
                                    if (Constant.Strings.SUC.equals(se.getCode())) {
                                        //ToastUtil.initToast(context, se.getMsg());
                                        dismiss();
                                        icListener.finishInvitateCode(se.getBody().getMember().getType()+"");
                                    } else {
                                        upTimeNum();
                                        ToastUtil.initToast(context, se.getMsg());
                                    }
                                }

                                @Override
                                public void onFailure(String url, String error) {
                                    dismissLoading();
                                }
                            });



                }
            }
        });


    }

    private void upTimeNum() {
        if (timeNum < retryLimit) {//倒计时中
            timeNum = 0;
        }
    }

    private void sendMsg() {
        loadingDialog = LoadingDialog.newInstance("发送中");
        loadingDialog.show(activity.getFragmentManager(), "loading");


        Map<String, Object> map = new HashMap<>();
        OkHttpUtil.postJson(context, Constant.URL.sms, new Sms(402, et_phone.getText().toString()), map, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                loadingDialog.dismiss();
                tv_send.setSelected(false);
                //upTimeNum();
                LogeUtil.e("sms", json);
                SmsEntity se = gson.fromJson(json, SmsEntity.class);
                if (Constant.Strings.SUC.equals(se.getCode())) {
                    ToastUtil.initToast(context, "发送成功");
                } else {
                    upTimeNum();
                    ToastUtil.initToast(context, "发送失败，请稍候重试");
                }

            }

            @Override
            public void onFailure(String url, String error) {
                loadingDialog.dismiss();
                tv_send.setSelected(false);
                upTimeNum();

            }
        });
        //设置XX秒后重试
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (tv_send != null) {
                    tv_send.setText("点击重新发送 (" + timeNum + ")");
                    if (timeNum > 0) {
                        handler.postDelayed(this, 1000);
                        timeNum--;
                    } else {
                        tv_send.setText("获取验证码");
                        timeNum = retryLimit;
                        tv_send.setSelected(false);
                    }
                }
            }
        });

    }

    public void setListener(FillInvitateCodeDialog.InvitateCodeListener icListener) {
        this.icListener = icListener;
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }

    }

    // 必须实现，这里返回您的contentView
    // 为了让库更加准确的做出适配，强烈建议使用createPopupById()进行inflate
    @Override
    public View onCreateContentView() {
        return createPopupById(R.layout.pop_vipyaoqingshengji);
    }


    private AnimationSet mAnimationSet;

    private void buildAnima() {
        ScaleAnimation mScaleAnimation = new ScaleAnimation(1f, 2f, 1f, 2f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        mScaleAnimation.setDuration(200);
        mScaleAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
        mScaleAnimation.setFillAfter(false);

        AlphaAnimation mAlphaAnimation = new AlphaAnimation(1, .2f);
        mAlphaAnimation.setDuration(400);
        mAlphaAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
        mAlphaAnimation.setFillAfter(false);

        mAnimationSet = new AnimationSet(false);
        mAnimationSet.setDuration(400);
        mAnimationSet.addAnimation(mScaleAnimation);
        mAnimationSet.addAnimation(mAlphaAnimation);
        mAnimationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismiss();
                    }
                }, 150);

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }


    @Override
    protected Animation onCreateShowAnimation() {
        Animation showAnima = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
                1f,
                Animation.RELATIVE_TO_PARENT,
                0,
                Animation.RELATIVE_TO_PARENT,
                0,
                Animation.RELATIVE_TO_PARENT,
                0);
        showAnima.setInterpolator(new DecelerateInterpolator());
        showAnima.setDuration(350);
        return showAnima;
    }

    @Override
    protected Animation onCreateDismissAnimation() {
        Animation exitAnima = new TranslateAnimation(Animation.RELATIVE_TO_PARENT,
                0f,
                Animation.RELATIVE_TO_PARENT,
                1f,
                Animation.RELATIVE_TO_PARENT,
                0,
                Animation.RELATIVE_TO_PARENT,
                0);
        exitAnima.setInterpolator(new DecelerateInterpolator());
        exitAnima.setDuration(350);
        return exitAnima;
    }


}


